using System;
using Microsoft.Practices.Unity;

namespace Sessionizer.Core.Unity
{
    public sealed class SessionsFactory<T> : ISessionsFactory<T>
    {
        private readonly IUnityContainer _container;
        private readonly ISessionsFactory<T> _realFactory;

        public SessionsFactory(IUnityContainer container)
        {
            _container = container;
            _realFactory = CreateRealFactory();
        }

        public T Create()
        {
            if (ReferenceEquals(_realFactory, null))
            {
                return _container.Resolve<T>();
            }
            return _realFactory.Create();
        }

        private ISessionsFactory<T> CreateRealFactory()
        {
            var dataType = typeof (T);
            if (Session.SessionBound && Session.Current.Configuration.IsDeclared(dataType))
            {
                return (ISessionsFactory<T>) _container.Resolve(Session.Current.Configuration.Declared(dataType));
            }
            return null;
        }
    }
}